package com.laijiale.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.laijiale.constant.ML;
import com.laijiale.dto.MenuInsertDTO;
import com.laijiale.dto.MenuPageDTO;
import com.laijiale.dto.MenuUpdateDTO;
import com.laijiale.entity.Menu;
import com.laijiale.exception.ServiceException;
import com.laijiale.mapper.MenuMapper;
import com.laijiale.service.MenuService;
import com.laijiale.vo.MenuSimpleListVO;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryChain;
import com.mybatisflex.core.update.UpdateChain;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

import static com.laijiale.entity.table.MenuTableDef.MENU;

/**
 * 服务层实现。
 *
 * @author laijiale
 * @since 2024-12-22
 */
@Service
@CacheConfig(cacheNames = "menu")
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements MenuService {

    @CacheEvict(allEntries = true)
    @Override
    public boolean insert(MenuInsertDTO dto) {
        Menu menu = BeanUtil.copyProperties(dto, Menu.class);
        //父菜单赋值
        if (ObjectUtil.isNull(dto.getPid())) {
            menu.setPid(ML.Menu.ROOT_ID);
            menu.setUrl("");
        }
        //标题查重
        if (QueryChain.of(mapper)
                .where(MENU.TITLE.eq(dto.getTitle()))
                .exists()) {
            throw new ServiceException("菜单标题已存在");
        }
        menu.setCreated(LocalDateTime.now());
        menu.setUpdated(LocalDateTime.now());
        return mapper.insert(menu) > 0;
    }

    @Cacheable(key = "#p0", condition = "#p0 != null", unless = "#result == null")
    @Override
    public Menu select(Long id) {
        return QueryChain.of(mapper)
                .where(MENU.ID.eq(id))
                .withRelations()
                .one();
    }

    @CacheEvict(allEntries = true)
    @Override
    public boolean update(MenuUpdateDTO dto) {

        // 标题查重
        if (QueryChain.of(mapper)
                .where(MENU.TITLE.eq(dto.getTitle()))
                .and(MENU.ID.ne(dto.getId()))
                .exists()) {
            throw new ServiceException("菜单标题已存在");
        }

        // 组装 entity 实体类
        Menu menu = BeanUtil.copyProperties(dto, Menu.class);
        menu.setUpdated(LocalDateTime.now());

        return UpdateChain.of(menu)
                .where(MENU.ID.eq(menu.getId()))
                .update();
    }

    @CacheEvict(allEntries = true)
    @Override
    public boolean delete(Long id) {
        return UpdateChain.of(mapper)
                .where(MENU.ID.eq(id)).remove();

    }

    @CacheEvict(allEntries = true)
    @Override
    public boolean deleteBatch(List<Long> ids) {
        return UpdateChain.of(mapper).where(MENU.ID.in(ids)).remove();
    }


    @Cacheable(key = "#root.methodName + ':' + #p0.toString()", unless = "#result == null")
    @Override
    public Page<Menu> page(MenuPageDTO dto) {
        QueryChain<Menu> queryChain = QueryChain.of(mapper);
        queryChain.orderBy(MENU.PID.asc(), MENU.IDX.asc(), MENU.ID.desc());

        // pid条件
        Long pid = dto.getPid();
        if (ObjectUtil.isNotNull(pid)) {
            queryChain.where(MENU.PID.eq(pid));
        }
        //title条件
        String title = dto.getTitle();
        if (ObjectUtil.isNotNull(title)) {
            queryChain.where(MENU.TITLE.like(title));
        }

        return queryChain.withRelations()
                .page(new Page<>(dto.getPageNum(), dto.getPageSize()));

    }
    @Cacheable(key = "#root.methodName",
                unless = "#result == null"
    )
    @Override
    public List<MenuSimpleListVO> simpleList() {
        //查询所有菜单
        List<Menu> menus =QueryChain.of(mapper).orderBy(MENU.PID.asc(),MENU.IDX.asc(),MENU.ID.desc()
                ).withRelations().list();
        //封装VO
        List<MenuSimpleListVO> menuSimpleListVOS=new ArrayList<>();
        menus.forEach(menu -> {
            MenuSimpleListVO menuSimpleListVO=BeanUtil.copyProperties(menu,MenuSimpleListVO.class);
            if (menu.getParentMenu()!=null){
                menuSimpleListVO.setParentTitle(menu.getParentMenu().getTitle());
            }
            menuSimpleListVOS.add(menuSimpleListVO);
        });

        return menuSimpleListVOS;
    }
}

